package com.xl.flinkdemo.sink输出操作;

import com.xl.flinkdemo.entity.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class SinkTest_JDBC {
    public static void main(String[] args) throws Exception {

        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        // 从文件中读取数据
        String inputPath = "D:\\myWork\\flinkdemo\\src\\main\\resources\\sensors";

        //得到数据源
        DataStream<String> inputdataStream = env.readTextFile(inputPath);
        DataStream<SensorReading> dataStream =
                inputdataStream.map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String s) throws Exception {
                        String[] fields = s.split(",");
                        return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
                    }
                });

        dataStream.addSink(new MyJdbcSink());
        env.execute();
    }

    public static class MyJdbcSink extends RichSinkFunction<SensorReading> {

        //声明连接和预编译属性
        Connection connection = null;
        PreparedStatement insertState = null;
        PreparedStatement updateState = null;

        @Override
        public void open(Configuration parameters) throws Exception {
            connection = DriverManager.getConnection("jdbc:mysql://192.168.78.133:3306/one","root","12345678");
            insertState = connection.prepareStatement("insert into sensor_temp value (?,?)");
            updateState = connection.prepareStatement("update sensor_temp set temp = ? where id =?");
        }

        @Override
        public void invoke(SensorReading value, Context context) throws Exception {
            updateState.setDouble(1,value.getSensors());
            updateState.setString(2,value.getId());
            boolean execute = updateState.execute();
            if(updateState.getUpdateCount()==0){
                insertState.setString(1,value.getId());
                insertState.setDouble(2,value.getSensors());
                insertState.execute();
            }
        }

        @Override
        public void close() throws Exception {
            insertState.close();;
            updateState.close();
            connection.close();
        }
    }
}
